import React from 'react';
import { Button, Card, Modal, Space, Table, message, TableProps } from 'antd';
import _ from 'lodash';
import dayjs from 'dayjs';
import { useParams } from 'react-router-dom';
import { APPROVAL_STATUS } from '@/constant';
import BorrowPopup from '../op/borrowPopup';
import { borrowRevoked, getBorrowTeacherList } from '@/service/teacher/borrow';
import { TeachersSrv } from '@/service/teacher';
import useCountry from '@/hooks/useCountry';
import { isPermissionOperate } from '@/component/permission-button';

const Groups: React.FC = () => {
  const [value, setValue] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [selectDataType, setSelectDataType] = React.useState<Array<any>>([]);
  //const location = useLocation();
  const [showBorrowoutForm, setShowBorrowoutForm] = React.useState(false);
  const { id } = useParams();
  const country = useCountry();

  const columns: TableProps['columns'] = [
    {
      title: '原任职单位',
      dataIndex: 'original_unit_name',
      key: 'original_unit_name',
    },
    {
      title: '原任职单位管辖区',
      dataIndex: 'original_region_area_id',
      key: 'original_region_area_id',
      render: (text, record) => {
        const r = _.find(country, { value: text });
        if (r) return _.find(country, { value: text })?.label;
        if (
          record.original_region_province_name &&
          record.original_region_city_name &&
          record.original_region_area_name
        )
          return `${record.original_region_province_name}/${record.original_region_city_name}/${record.original_region_area_name}`;
        return '/';
      },
    },
    {
      title: '原任职单位行政区',
      dataIndex: 'original_district_area_id',
      key: 'original_district_area_id',
      render: (text, record) => {
        const r = _.find(country, { value: text });
        if (r) return _.find(country, { value: text })?.label;
        if (
          record.original_district_province_name &&
          record.original_district_city_name &&
          record.original_district_area_name
        )
          return `${record.original_district_province_name}/${record.original_district_city_name}/${record.original_district_area_name}`;
        return '/';
      },
    },
    {
      title: '现任职单位',
      dataIndex: 'current_unit_name',
      key: 'current_unit_name',
    },
    {
      title: '现任职单位管辖区',
      dataIndex: 'current_region_area_id',
      key: 'current_region_area_id',
      render: (text, record) => {
        const r = _.find(country, { value: text });
        if (r) return _.find(country, { value: text })?.label;
        if (record.current_region_province_name && record.current_region_city_name && record.current_region_area_name)
          return `${record.current_region_province_name}/${record.current_region_city_name}/${record.current_region_area_name}`;
        return '/';
      },
    },
    {
      title: '现任职单位行政区',
      dataIndex: 'current_district_area_id',
      key: 'current_district_area_id',
      render: (text, record) => {
        const r = _.find(country, { value: text });
        if (r) return _.find(country, { value: text })?.label;
        if (
          record.current_district_province_name &&
          record.current_district_city_name &&
          record.current_district_area_name
        )
          return `${record.current_district_province_name}/${record.current_district_city_name}/${record.current_district_area_name}`;
        return '/';
      },
    },
    {
      title: '审批人',
      dataIndex: 'approval_name',
      key: 'approval_name',
    },
    {
      title: '审批状态',
      dataIndex: 'approval_status',
      key: 'approval_status',
      render: (text, record) => {
        if (text) return _.find(APPROVAL_STATUS, { value: String(text) })?.label;
        return text;
      },
    },
    {
      title: '申请时间',
      dataIndex: 'start_time',
      key: 'start_time',
      render: (text, record) => {
        if (text && dayjs(text).isValid()) return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
        return text;
      },
    },
    {
      title: '审批时间',
      dataIndex: 'approval_time',
      key: 'approval_time',
      render: (text, record) => {
        if (text && dayjs(text).isValid()) return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
        return text;
      },
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space size="middle">
          {['pending'].includes(record.approval_status) && (
            <Button
              type="link"
              onClick={async () => {
                Modal.confirm({
                  title: '撤回',
                  content: `是否撤回${record.teacher_name}调出?`,
                  onOk: async () => {
                    const res = await borrowRevoked(record.id);
                    if (res.success) {
                      message.success('撤回成功');
                    } else message.error(res.message || res.details);
                  },
                });
              }}
            >
              撤回
            </Button>
          )}
          {['revoked'].includes(record.approval_status) && record.transfer_type === 'transfer_out' && (
            <Button
              type="link"
              onClick={() => {
                setSelectDataType([
                  {
                    teacher_id: record.teacher_id,
                    teacher_name: record.teacher_name,
                    teacher_id_number: record.teacher_id_number,
                    teacher_sub_status: record.teacher_sub_status,
                  },
                ]);
                setShowBorrowoutForm(true);
                console.log('重新提交');
              }}
            >
              重新提交
            </Button>
          )}
          {['approved'].includes(record.teacher_sub_status) && (
            <Button
              onClick={() => {
                const res: any = TeachersSrv.activeByBorrow(record.teacher_id, record.process_instance_id);
                if (res.success) {
                  message.success('操作成功');
                } else {
                  message.error(res.message || res.details);
                }
              }}
            >
              恢复在职
            </Button>
          )}
        </Space>
      ),
    },
  ];
  const searchFunc = async () => {
    setLoading(true);
    const res = await getBorrowTeacherList(id);
    if (res.success) {
      //setTotal(res.data.total);
      setValue(res.data);
      // setPageIndex(pageIndex);
      // setPageSize(pageSize);
    }
    setLoading(false);
  };
  // const pageChange = (pageIndex, pageSize) => {
  //   set_stoge_pz(pageSize, 'change_borrow');
  //   searchFunc(pageIndex, pageSize);
  // };
  React.useEffect(() => {
    searchFunc();
  }, []);
  return (
    <Card title="借动信息" bordered={false}>
      <Table
        dataSource={value}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        //pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <BorrowPopup
        onFinish={() => searchFunc()}
        showTransferoutForm={showBorrowoutForm}
        setShowTransferoutForm={setShowBorrowoutForm}
        selectDataType={selectDataType}
      />
    </Card>
  );
};
export default Groups;
